#!/usr/bin/env python
# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
 
class StockQuant(models.Model):
    _inherit = 'stock.quant' 

    def check_expired_products(self):
        res = self.check_expired_products_to_scrap(only_create_batch=True)
        batch_row = res.get('batch', False)
        if batch_row:
            batch_row.action_create_back_to_stock()
            batch_row.action_create_quality_checks()

    def check_expired_products_to_scrap(self, only_create_batch=False):
        stock_code = self.env.ref('stock.stock_location_stock')
        check_code = self.env.ref('sb_product_expiry_ext.stock_location_quality_control')
        expired_quants = self.search([ 
            ('lot_id', '!=', False),
            ('product_id.use_expiration_date',  '=', True),
            ('lot_id.expiration_date',  '<', fields.Date.today()) ,
            '|',
            ('location_id', '=', stock_code.id),
            ('location_id.location_id', '=', stock_code.id),
        ])
        if not expired_quants:
            return {}
        picking_type = self.env.ref('sb_product_expiry_ext.picking_type_expired_quality')
        batch = self.env['expired.quality.batch'].create({'date':  fields.Date.today()}) 
        moves = self.env['stock.move'] 
        picking_id = self.env['stock.picking'].create({
            'picking_type_id': picking_type.id,
            'location_id':stock_code.id,
            'location_dest_id': check_code.id, 
        })
        for quant in expired_quants:
            move = self.env['stock.move'].create({ 
                'picking_id': picking_id.id,
                'name': f'过期品处理-{quant.product_id.name}', 
                'product_id': quant.product_id.id, 
                'product_uom_qty': quant.quantity, 
                'location_id': quant.location_id.id, 
                'location_dest_id': check_code.id, 
                'picking_type_id': picking_type.id,
                'batch_id': batch.id,
                'lot_ids': [(4, quant.lot_id.id)],
                'move_line_ids': [(0, 0, {
                    'product_id': quant.product_id.id,
                    'lot_id': quant.lot_id.id,
                    'qty_done': quant.quantity,
                    'location_id': quant.location_id.id,
                    'location_dest_id': check_code.id,
                })]
            })
            moves += move 
        moves._action_confirm()
        #  moves._action_assign()
        #  moves._action_done()
        try:
            picking_id.button_validate() 
        except UserError as e:
            raise ValidationError(_("完成库存到到期品检单据出错：{error}").format(error=e))
        return {'batch':batch, 'picking':picking_id}
